package com.nulldev.util.java.scripting.nscript.jengine;

import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;

import javax.script.AbstractScriptEngine;
import javax.script.Bindings;
import javax.script.ScriptContext;
import javax.script.ScriptEngineFactory;
import javax.script.ScriptException;
import javax.script.SimpleBindings;

import com.nulldev.util.java.scripting.nscript.nScript;

public class nScriptEngine extends AbstractScriptEngine {

	@Override
	public Object eval(String script, ScriptContext context) throws ScriptException {
		final nScript ns = new nScript(script);
		ns.run();
		return ns.read();
	}

	@Override
	public Object eval(Reader reader, ScriptContext context) throws ScriptException {
		String s = "";
		int r = 0;
		try {
			while ((r = reader.read()) != -1) {
				s += (char) r;
			}
		} catch (IOException e) {
			throw new ScriptException(e);
		}
		final nScript ns = new nScript(s);
		ns.run();
		return ns.read();
	}

	private List<Bindings> bindings = new ArrayList<Bindings>();
	
	@Override
	public Bindings createBindings() {
		final Bindings b = new SimpleBindings();
        this.bindings.add(b);
        return b;
	}

	@Override
	public ScriptEngineFactory getFactory() {
		return nScriptEngineFactory.INSTANCE;
	}

}
